<?php

namespace App\Exceptions;

use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Throwable;
use Illuminate\Validation\ValidationException;
use Illuminate\Contracts\Container\BindingResolutionException;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Database\QueryException;
use Illuminate\Support\Facades\Log;
use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

class Handler extends ExceptionHandler
{
    /**
     * The list of the inputs that are never flashed to the session on validation exceptions.
     *
     * @var array<int, string>
     */
    protected $dontFlash = [
        'current_password',
        'password',
        'password_confirmation',
    ];

    /**
     * Register the exception handling callbacks for the application.
     */
    public function register(): void
    {
        $this->reportable(function (Throwable $e) {
            //
        });
    }
    public function render($request, Throwable $exception)
    {


        if(strpos($exception->getMessage(),'Data too long for column')!==false || strpos($exception->getMessage(),'Out of range value for column')!==false){
            return response()->json([
                'code' => '001', 'msg' => '您的输入已超出限制，请重新输入！'
            ]);
        }



        if ($exception instanceof NotFoundHttpException) {
            return response()->json([
                'code' => 404, 'msg' => 'Api Not Found'
            ], 404);
        }
        if ($exception instanceof MethodNotAllowedHttpException) {
            return response()->json([
                'code' => 404, 'msg' => 'Api Not Found'
            ], 404);
        }
        if ($exception instanceof BindingResolutionException) {
            return response()->json([
                'code' => 501, 'msg' => $exception->getMessage()
            ], 500);
        }
        if ($exception instanceof ModelNotFoundException) {
            return response()->json([
                'code' => 502, 'msg' => $exception->getMessage()
            ], 500);
        }
        if ($exception instanceof ValidationException) {
            return response()->json([
                'code' => 503, 'msg' => $exception->getMessage()
            ], 500);
        }
        if ($exception instanceof QueryException) {
            return response()->json([
                'code' => 504, 'msg' => $exception->getMessage()
            ], 500);
        }
        if ($exception instanceof \Exception) {
            return response()->json([
                'code' => 505, 'msg' => $exception->getTraceAsString()
            ], 500);
        }

        return response()->json([
            'code' => 500, 'msg' => $exception->getMessage()
        ], 500);
    }
}
